package logic

import (
	"context"

	"mqtt/internal/svc"
	"mqtt/mqtt"

	"github.com/zeromicro/go-zero/core/logx"
)

type PublishLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPublishLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PublishLogic {
	return &PublishLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 发布消息到指定主题
func (l *PublishLogic) Publish(in *mqtt.PublishRequest) (*mqtt.PublishResponse, error) {
	// 调用客户端管理器发布消息
	err := l.svcCtx.ClientMgr.Publish(in.ServerAddr, in.Topic, in.Payload, int32(in.Qos), in.Retain)
	if err != nil {
		return &mqtt.PublishResponse{
			Success: false,
			Error:   err.Error(),
		}, nil
	}

	return &mqtt.PublishResponse{
		Success: true,
	}, nil
}
